package server

import (
	"fmt"
	"log"
	"net/http"
	"path/filepath"
	"time"

	"com.zkh/agent/coap/conf"
	"com.zkh/agent/coap/service"
	"github.com/gin-gonic/gin"
)

func HttpServer() {

	gin.SetMode(gin.DebugMode)
	r := gin.New()
	v1 := r.Group("/coapApi/v1")
	{
		// 平台调用 coap 服务
		v1.POST("/cmd", service.DoCmd)

	}

	address := fmt.Sprintf("0.0.0.0:%d", conf.GetHttpPort())
	s := &http.Server{
		Addr:              address,
		ReadHeaderTimeout: 60 * time.Second,
		IdleTimeout:       120 * time.Second,
		Handler:           r,
	}
	defer s.Close()

	log.Printf("HttpServer Will Listening on https: %v\n", address)

	err := s.ListenAndServeTLS(
		filepath.Join("data/", "server.crt"),
		filepath.Join("data/", "server.key"),
	)
	// 如果https 开启失败则开启 http
	if err != nil {
		log.Printf("Https ListenAndServeTLS error : %v\n", err)
		log.Printf("HttpServer Now Listening on http: %v\n", address)
		err = s.ListenAndServe()
	}

}
